<?php
/*
*
* 一个集成MySQL数据库操作和数据缓存的php简易类
* 
*    <pre>
*     email:s_jqzhang@163.com
*     website:http://hi.baidu.com/s_jqzhang
*     @author:小张 
*    </pre>
* */

/**
* @desc EasyPHP 核心类
*/
  class EasyPHP
{    /*基本配置*/ 
     public $cfg=array(
     
     //应用设置
     "app_name"=>"EasyPHP",
     
     "db_host"=>"127.0.0.1", //数据库地址
     "db_port"=>"3306",  //数据库端口
     "db_user"=>"root", //数据库用户名
     "db_pwd"=>"", //数据库密码
     "db_name"=>"test",  //数据库名称
     "db_charset"=>"utf8", //数据库字符集
     "db_type"=>"mysql",  //数据库类型  mysql  , mssql ,
     //odbc     odbc连接access array(db_host=> "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("test.mdb") )
     "debug"=>false,  //是否开启调试
     "show_sql"=>false,
     "ajax_return_type"=>"json",
     "log_path"=>"log",
     "log_file_name"=>"log.txt",//记录日志文件后缀
     "log_type"=>"1", //0表示直接显示,1表示写入日志文件,2表示直接显示并写入日志 -1表示不作日志   
     "run_time"=>0.00001,//系统行运时间
     //出错发邮件设置
     "mail_to"=>"easyphp.163.com",
     "log_mail"=>true,
     
     
     //cookie设置
     "COOKIE_PREFIX"=>"cookie", // cookie 名称前缀
     "COOKIE_PATH"=>"",  // cookie 保存路径
     "COOKIE_EXPIRE"=>"", //cookie 保存时间
     "COOKIE_DOMAIN"=>"",  // cookie 有效域名
     "session_name"=>"PHPSESSID",
     //缓存方式
     "cache_type"=>1,//0文件缓存,1数据库缓存
     //文件缓存设置
     "cache_on"=>false,
     "cache_path"=>"cache",//缓存路径
     "cache_time"=>3,  //缓存时间,单位秒
     //数据库缓存设置
     "db_cache_on"=>false,     //是否开启数据库缓存
     "db_cache_table"=>"cache",//缓存数据表名
     "db_cache_time"=>50,  //缓存时间,单位秒 
     //数据库session
     "db_session_on"=>false,     //是否开启数据库缓存
     "db_session_table"=>"session",//缓存数据表名
     "db_session_time"=>50,  //缓存时间,单位秒 
     //文件上传
     "file_path"=>"./upload",  //上传路径
     "file_size"=>4096,  //上传文件的大小
     "file_ext"=>"*",   //上传文件的扩展名  *表示所有, 格式如: jpg|doc|rar
     
     //ftp设置
     "ftp_host"=>"127.0.0.1",
     "ftp_port"=>21,
     "ftp_user"=>"anonymous",
     "ftp_pwd"=>"",
     //email设置
     "mail_host"=>"smtp.163.com",
     "mail_port"=>25,
     "mail_user"=>"s_jqzhan",
     "mail_pwd"=>"123",
     //Action配置
     "action"=>"",
     "action_file"=>"",
     "action_path"=>"", 
     "action_class"=>"",
     "action_param"=>array(),
     
    
     );
     public $error;
     public $db;      //数据库操作类实例
     public $paras=array();    //网面POST或GET方式传递过来的参数
     public $cache;
     public $dbcache;
     /**
     * @desc 数据库session
     * @var   $dbsession 用于存放DBSession实例
     */
     public $dbsession;

     

     /**
     * @desc   构造函数
     * @param  array 初始化数组
     * <pre>
     * 使用实例
     * </pre>
     * <pre>
     *  $easy=new EasyPHP(array("db_pwd"=>"root",
     * "db_user"=>"root","debug"=>true));
     * </pre>
     *  */
     
     public  function  __construct($config=array())//注意构造函数的参数必须是数组
    {                                                                                 
       $this->cfg=array_change_key_case(array_merge($this->cfg,$config)); //合并初始化参数   
      // $this->end();
      // print_r($this->cfg); 
       $this->init();            //初始化EasyPHP
       $this->initParas();       //初始化POST GET方式参数    
       if($this->C("db_type")=="mysql")
       $this->db=new MySQL($this->cfg);     //初始化MySQL类，以便更方便操作数据库
       if($this->C("db_type")=="mssql")  
       $this->db=new MSSQL($this->cfg);     //初始化MySQL类，以便更方便操作数据库
       if($this->C("db_type")=="odbc")  
       $this->db=new ODBC($this->cfg);     //初始化MySQL类，以便更方便操作数据库
       
       //$this->db->config($this->cfg);     //设置数据库参数
       $this->db->paras=$this->paras;    //初始化网页参数
       $this->cache=new Cache($this->cfg);     //实例化缓存类
      // $this->cache->config($this->cfg); //设置缓存类
      // $this->cache->init();             //初始化缓存类
       $this->db->cache=$this->cache;    //初始化数据库缓存
       error_reporting(E_ERROR | E_WARNING | E_PARSE); //处理自定义错误的类型
       set_error_handler(array(&$this,'errorHandler'));//自定错误
       $this->run_start();//开始计时
       
       $this->dbcache=new DbCache(); //实例数据库缓存
       $this->dbcache->db=$this->db;//设置数据缓存数据库
       $this->dbcache->config($this->cfg); //设置数据库缓存
       $this->db->dbcache=$this->dbcache;//设置数据库缓存
       
       $this->dbsession=new DbSession();
       $this->db->dbsession=$this->dbsession; 
       $this->dbsession->db=$this->db;
       $this->dbsession->config($this->cfg);
         //开启session支持 
        if((!isset($_SESSION))&&(!$this->C("db_session_on")))
        {
        session_start();
        } 
       
       
       @ini_set('date.timezone','Asia/Shanghai');//时区设置
       @ini_set("session.name",$this->C('session_name'));
       
       //初始化session
      if( $this->C("db_session_on"))
      {
       
        $domain = '';
        //不使用 GET/POST 变量方式
        ini_set('session.use_trans_sid',0);
        //设置垃圾回收最大生存时间
        ini_set('session.gc_maxlifetime',$this->C("db_session_time"));
        //使用 COOKIE 保存 SESSION ID 的方式
        ini_set('session.use_cookies',0);
        ini_set('session.cookie_path','/');
        //多主机共享保存 SESSION ID 的 COOKIE,因为我是本地服务器测试所以设置$domain=''
        ini_set('session.cookie_domain',$domain);
        //将 session.save_handler 设置为 user，而不是默认的 files
        session_module_name('user');
          
       session_set_save_handler(array(&$this->dbsession,"open"), 
                         array(&$this->dbsession,"close"), 
                         array(&$this->dbsession,"get"), 
                         array(&$this->dbsession,"set"), 
                         array(&$this->dbsession,"destroy"), 
                         array(&$this->dbsession,"gc")); 
        if(!isset($_SESSION))
        {
        session_start();
        }
      }
     
     
       // $_SERVER['PHP_SELF']=  $_SERVER['PHP_SELF']."?sessionid=".session_id(); 
      
    
      //$this->out($_SERVER );
      //$this->out($_SERVER );
      //$this->out( );
      
      
      
      
       
       
    }
    /**
    *析构函数
    * */ 
     public  function __destruct()
    {
          // $this->cache->clear();
    }
    /**
    *
    * 初始化
    * */ 
    public function init()
    {
       if(!file_exists($this->C("cache_path")))
       {
          $this->creatdir($this->C("cache_path"));
       }
       if(!file_exists($this->C("log_path")))
       {
          $this->creatdir($this->C("log_path"));
       }
      $this->actionPath(rtrim($_SERVER["SCRIPT_NAME"],'/'));
      $this->run_start();
    }
    /**
    *
    * 设设属性
    * 
    * @param  $name string 属性名称
    * @param  $value mixed 属性值
    * */
    public function __set($name,$value)
    {
        if(property_exists($this,$name))
        $this->$name=$value;
    }
    /**
    *
    * 取属性 
    * 
    * @param $name string 属性名称
    * @return mixed 属性值
    * */ 
    public function __get($name)
    {
         if(property_exists($this,$name))
         return $this->$name;
    }
    /**
    *
    * 生成json数据
    * 
    * @param $value mixed 要生成json数据的值
    * */ 
    public function jsonEncode($value)
    {
        return json_encode($value);
    }
    /**
    *
    * 脚本开始计时
    * 
    * <pre>
    * $easy->run_start();//脚本计时开始
    * $easy->run_time();//取得脚本运行时间
    * </pre>
    * */ 
    function run_start()
    {
       $this->C(array("run_time"=>microtime(true)));   
    }
    /**
    *
    * 内存使用量
    * */ 
    function use_mem()
    {
      $u=  memory_get_usage();
      if(($u/1024/1024)>1)
      {
         return round(($u/1024/1024),2)." Mb";
      }
      else
      {
          return round(($u/1024),2)." Kb";   
      }  
    }
    /**
    *
    * @desc取得运行时间
    * 
    * <pre>
    * $easy->run_start();//脚本计时开始
    * $easy->run_time();//取得脚本运行时间
    * </pre>
    * */ 
    public function run_time()
    {
     return round((microtime(true)-$this->C("run_time")),4)." S";   
    }
    /**
    * @desc 取得系统当前日期和时间
    */
    public function now($format="")
    {
        if(empty($format))
        {
        return date('Y-m-d H:i:s');    
        }
        else
        {
            return date($format);  
        }
    }
    /**
    * @desc 取是系统日期
    */
     public function date($format="")
    {
        if(empty($format))
        {
        return date('Y-m-d');    
        }
        else
        {
            return date($format);  
        }
    }
    
    
    
     /**
 * 将字符串转换成unicode编码
 *
 * @param string $input
 * @param string $input_charset
 * @return string
 */
function str2unicode($input, $input_charset = 'gbk'){
 $input = iconv($input_charset, "gbk", $input);
 preg_match_all("/[\x80-\xff]?./", $input, $ar);
 $b = array_map( array(&$this, 'utf8_unicode_'), $ar[0]);
 $outstr = join("", $b);
 return $outstr;
}

function utf8_unicode_($c, $input_charset = 'gbk'){
 $c = iconv($input_charset, 'utf-8', $c);
 return $this->utf8_unicode($c);
}
// utf8 -> unicode
function utf8_unicode($c) {
 switch(strlen($c)) {
 case 1:
 return $c;
 case 2:
 $n = (ord($c[0]) & 0x3f) << 6;
 $n += ord($c[1]) & 0x3f;
 break;
 case 3:
 $n = (ord($c[0]) & 0x1f) << 12;
 $n += (ord($c[1]) & 0x3f) << 6;
 $n += ord($c[2]) & 0x3f;
 break;
 case 4:
 $n = (ord($c[0]) & 0x0f) << 18;
 $n += (ord($c[1]) & 0x3f) << 12;
 $n += (ord($c[2]) & 0x3f) << 6;
 $n += ord($c[3]) & 0x3f;
 break;
 }
 return "&#$n;";
}

/**
* 将unicode转为字符串
*  
* @param string $str
* @param mixed $out_charset
* @return string
*/
 
 function unicode2str($str, $out_charset = 'gbk'){
 $str = preg_replace_callback("|&#([0-9]{1,5});|", array(&$this,'unicode2utf8_'), $str);
 $str = iconv("UTF-8", $out_charset, $str);
 return $str;
}

function unicode2utf8_($c){
 return $this->unicode2utf8($c[1]);
}
function unicode2utf8($c){
 $str="";
 if ($c < 0x80) {
 $str.=$c;
 } else if ($c < 0x800) {
 $str.=chr(0xC0 | $c>>6);
 $str.=chr(0x80 | $c & 0x3F);
 } else if ($c < 0x10000) {
 $str.=chr(0xE0 | $c>>12);
 $str.=chr(0x80 | $c>>6 & 0x3F);
 $str.=chr(0x80 | $c & 0x3F);
 } else if ($c < 0x200000) {
 $str.=chr(0xF0 | $c>>18);
 $str.=chr(0x80 | $c>>12 & 0x3F);
 $str.=chr(0x80 | $c>>6 & 0x3F);
 $str.=chr(0x80 | $c & 0x3F);
 }
 return $str;
}

/**
 * 模拟JS里的unescape
 *
 * @param unknown_type $str
 * @return unknown
 */

function unescape($str) {
 $str = rawurldecode($str);
 preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
 $ar = $r[0];
 #print_r($ar);
 foreach($ar as $k=>$v) {
 if(substr($v,0,2) == "%u")
 $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
 elseif(substr($v,0,3) == "")
 $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
 elseif(substr($v,0,2) == "&#") {
 echo substr($v,2,-1)."
";
 $ar[$k] = iconv("UCS-2","GB2312",pack("n",substr($v,2,-1)));
 }
 }
 return join("",$ar);
}
    
    /**
    *
    * json到数据
    * */ 
    public function jsonDecode($json)
    {
        return json_decode($json);
    }
    /**
    *
    * 取得IP
    * 
    * @return string 返回客户端的IP地址
    * 
    * <pre>
    *   $easy->getIp();
    * </pre>
    * */
    public function getIp()
    {
         if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
            $ip = getenv ( "HTTP_CLIENT_IP" );
        else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
            $ip = getenv ( "HTTP_X_FORWARDED_FOR" );
        else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
            $ip = getenv ( "REMOTE_ADDR" );
        else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
            $ip = $_SERVER ['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return $ip;   
    }
    /**
    *
    *@desc 截取字符串
    * 
    * @param $str string 要截取的字符串 
    * @param $start int 起始编号
    * $param $len int 截取的字符串的长度
    * <pre>
    * $easy->substring("hello easyphp",0,5);//返回  hello
    * </pre>
    * */ 
    function substring($str, $start, $len) 
    {
     $tmpstr = "";
     $strlen = $start + $len;
     for($i = 0; $i < $strlen; $i++) {
         if(ord(substr($str, $i, 1)) > 0xa0) {
             $tmpstr .= substr($str, $i, 2);
             $i++;
         } else
             $tmpstr .= substr($str, $i, 1);
     }
     return $tmpstr;
    }
    
   /**
   * 判断字符串是不是GBK
   *  
   * @param mixed $str   要判断的字符串
   * @return   真或假
   */
    
    function isGBK($str)
    {
      for($i=0;$i<strlen($str);$i++)
      {
         if(ord($str)>0x80) $i++;
         else return false;
      }
      return true;
    }
    /**
   * 判断字符串是不是GBK
   *  
   * @param mixed $str   要判断的字符串
   * @return   真或假
    */
    function isUTF8($string)
    {                
       $string_utf8 = utf8_encode($string);
       if( strpos($string_utf8,"",0) !== false ) // "" is ALT+159
             return true;  // the original string was utf8
       else
             return false; // otherwise
    } 
    
    /**
    *
    * @desc 设置配置文件
    * 
    * <ul>
    * <li>
    * 如果$c是字集串时返回该名称的值,
    * </li>
    * <li>
    * 如果$c是数组时则设置配置值
    * </li>
    * </ul>
    * <pre>
    *      $easy->C("db_host");//取得db_host的值
    *      $easy->C(array("db_host"=>"127.0.0.1"));/设置db_host的值
    * </pre>
    * 
    * @param $C mixed
    * */ 
    function C($c)
    {
       if(is_array($c))
       { 
         $c= array_change_key_case($c);
         foreach ($c as $key => $value) {
          $this->cfg[$key]=$value;  
         }           
       }
       else
       {
           if(isset($this->cfg[$c]))
           {
           return $this->cfg[$c];
           }
           else
           {
           return null;
           }  
       } 
    }
    /**
    *日志函数
    * 
    * 记录日志或输出日志
    * 
    * @param   $message string 日志信息
    * @param    $type int 0-直接输出,1-记录到日志文件,2-直接输出,并记录日志文件
    * <pre>
    * $easy->log("出错了",0);
    * </pre>
    * */ 
    function log($message,$type="0")
    {
        
       $i=$this->cfg["log_type"];     
       switch ($i) {
          case 0:
            $this->out($message);
            break;
          case 1:
            $this->log2file($message);
            break;
          case 2:
            $this->out($message);
            $this->log2file($message);
            break;
       }
        
    }
    /**
    *
    * 将日志写到文件
    * 
    * <pre>
    * $easy->log2file("出错了");//写入日志文件
    * </pre>
    * */ 
    function log2file($message)
    {
      date_default_timezone_set("PRC");
      $this->writefile( $this->C("log_path").'/'.date("Y-m-d-").$this->cfg["log_file_name"],date("Y-m-d H:i:s")."\t".$this->getIp()."\t".$message."\r\n");
    }
    /**
    *读文件
    * 
    * @param $filename string 文件名
    * @param $mode string 读取文件的模式 "r"
    * <pre>
    *      $easy->readfile("aa.txt");//读取aa.txt的文本内容
    * </pre>
    * */ 
    function readfile($filename,$mode="r")
    {
       if(file_exists($filename))
       { 
       $f=fopen($filename,$mode);
       $content= fread($f,filesize($filename));
       fclose($f); 
       return $content;
       }
       else
       {
           return "";
       } 
    }
    /**
    *写文件
    * 
    * @param $filename string 文件名
    * @param $content string 写入的内容
    * @param $mode string 写入的模式  "a+", "w+",.. 
    * <pre>
    *   $easy->writefile("aa.txt","Hello EasyPHP","a+");//追加文件内容
    * </pre>
    * */ 
    function writefile($filename,$content,$mode="a+")
    {
        $f=fopen($filename,$mode);
        fwrite($f,$content);
        fclose($f);
    }
    /**
    *创建目录
    * 
    * @param $path string 路径
    * <pre>
    * $easy->creatdir("a/b/c/d/e");  创建多层目录
    * </pre>
    * */ 
    function creatdir($path)
    {
        $dir='';
        $path = split('[/]', $path);
        if(is_array($path))
        {
                foreach($path as $v)
                {
                    
                    $dir .= $v;
                    if(!file_exists($dir)&&(!empty($dir)))
                        mkdir($dir,0700);
                    $dir .= '/';
                }
        }
    }
    /**
    *错误处理
    * */ 
     function errorHandler($errno, $errstr, $errfile, $errline)
    {
      switch ($errno) {
          case E_ERROR:
          case E_USER_ERROR:
            $errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
             if($this->C("debug"))
             $this->out($errorStr);
             if(($this->C("log_type")==1)||($this->C("log_type")==2))
              $this->log2file($errorStr);
              if(class_exists("EasyMail")&&($this->C("log_mail")))
             {
               $mail=new EasyMail($this->cfg);
               $mail->sendmail($this->C("mail_to"),$this->C("mail_to"),$this->C("app_name"),iconv("utf-8","gbk", $errorStr),'TXT');
             }
              halt($errorStr);
            break;
          case E_STRICT:
          case E_USER_WARNING:
          case E_USER_NOTICE:
          default:
            $errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
            echo $errorStr;
            if($this->C("debug"))
            $this->out($errorStr);
            if(($this->C("log_type")==1)||($this->C("log_type")==2))
             $this->log2file($errorStr); 
             if(class_exists("EasyMail")&&($this->C("log_mail")))
             {
               $mail=new EasyMail($this->cfg);
               $mail->sendmail($this->C("mail_to"),$this->C("mail_to"),$this->C("app_name"),iconv("utf-8","gbk", $errorStr),'TXT');
             }
           
              
            break;
      }
    }
    /**
    *去除代码中的空白和注释
    * */
    function stripphp($content) {
        $stripStr = '';
        //分析php源码
        $tokens =   token_get_all ($content);
        $last_space = false;
        for ($i = 0, $j = count ($tokens); $i < $j; $i++)
        {
            if (is_string ($tokens[$i]))
            {
                $last_space = false;
                $stripStr .= $tokens[$i];
            }
            else
            {
                switch ($tokens[$i][0])
                {
                    //过滤各种PHP注释
                    case T_COMMENT:
                    case T_DOC_COMMENT:
                        break;
                    //过滤空格
                    case T_WHITESPACE:
                        if (!$last_space)
                        {
                            $stripStr .= ' ';
                            $last_space = true;
                        }
                        break;
                    default:
                        $last_space = false;
                        $stripStr .= $tokens[$i][1];
                }
            }
        }
        return $stripStr;
    }
    /**
    *数据转XML
    * */
   public function data2xml($data) 
    {
        if(is_object($data)) {
            $data = get_object_vars($data);
        }
        $xml = '';
        foreach($data as $key=>$val) {
            is_numeric($key) && $key="item id=\"$key\"";
            $xml.="<$key>";
            $xml.=(is_array($val)||is_object($val))?$this->data2xml($val):$val;
            list($key,)=explode(' ',$key);
            $xml.="</$key>";
        }
        return $xml;
    }
    /**
    *
    * xml编码
    * <pre>
    *      $easy-> xmlencode($easy->db->query2array("select * from news"),"utf-8","news");//将新闻数组转化成xml格式
    * </pre>
    * */
    function xmlencode($data,$encoding='utf-8',$root="root")
     {
        $xml = '<?xml version="1.0" encoding="'.$encoding.'"?>';
        $xml.= '<'.$root.'>';
        $xml.= $this->data2xml($data);
        $xml.= '</'.$root.'>';
        return $xml;
    }
    //cookie设置
      /**
     * 1 获取cookie: cookie('name')
     * 2 清空当前设置前缀的所有cookie: cookie(null)
     * 3 删除指定前缀所有cookie: cookie(null,'think_') | 注：前缀将不区分大小写
     * 4 设置cookie: cookie('name','value') | 指定保存时间: cookie('name','value',3600)
     * 5 删除cookie: cookie('name',null)
     +----------------------------------------------------------
     * $option 可用设置prefix,expire,path,domain
     * 支持数组形式:cookie('name','value',array('expire'=>1,'prefix'=>'think_'))
     * 支持query形式字符串:cookie('name','value','prefix=tp_&expire=10000')
     * 
    */
    function cookie($name,$value='',$option=null)
    {
        // 默认设置
        $config = array(
            'prefix' => $this->C('COOKIE_PREFIX'), // cookie 名称前缀
            'expire' => $this->C('COOKIE_EXPIRE'), // cookie 保存时间
            'path'   => $this->C('COOKIE_PATH'),   // cookie 保存路径
            'domain' => $this->C('COOKIE_DOMAIN'), // cookie 有效域名
        );
        // 参数设置(会覆盖黙认设置)
        if (!empty($option)) {
            if (is_numeric($option))
                $option = array('expire'=>$option);
            elseif( is_string($option) )
                parse_str($option,$option);
            array_merge($config,array_change_key_case($option));
        }
        // 清除指定前缀的所有cookie
        if (is_null($name)) {
           if (empty($_COOKIE)) return;
           // 要删除的cookie前缀，不指定则删除config设置的指定前缀
           $prefix = empty($value)? $config['prefix'] : $value;
           if (!empty($prefix))// 如果前缀为空字符串将不作处理直接返回
           {
               foreach($_COOKIE as $key=>$val) {
                   if (0 === stripos($key,$prefix)){
                        setcookie($_COOKIE[$key],'',time()-3600,$config['path'],$config['domain']);
                        unset($_COOKIE[$key]);
                   }
               }
           }
           return;
        }
        $name = $config['prefix'].$name;
        if (''===$value){
            return isset($_COOKIE[$name]) ? unserialize($_COOKIE[$name]) : null;// 获取指定Cookie
        }else {
            if (is_null($value)) {
                setcookie($name,'',time()-3600,$config['path'],$config['domain']);
                unset($_COOKIE[$name]);// 删除指定cookie
            }else {
                // 设置cookie
                $expire = !empty($config['expire'])? time()+ intval($config['expire']):0;
                setcookie($name,serialize($value),$expire,$config['path'],$config['domain']);
                $_COOKIE[$name] = serialize($value);
            }
        }
    }
   /**
   * 判断是否为手机访问
   *  
   */
    function isPhone()
    {
        if (isset($_SERVER['HTTP_ACCEPT']) && 
    (strpos($_SERVER['HTTP_ACCEPT'],'vnd.wap.wml')!==FALSE)
    && (strpos($_SERVER['HTTP_ACCEPT'],'text/html')===FALSE ||
    (strpos($_SERVER['HTTP_ACCEPT'],'vnd.wap.wml') < 
        strpos($_SERVER['HTTP_ACCEPT'],'text/html'))
    )) { return true;
} else {
    return false;
}

    }
    /**
    *简单输出
    * 
    * 简单输出,如果$content不是数组直接echo ,否则用print_r($content)输出
    * <pre>
    *      $easy->out("Hello EasyPHP");
    * </pre>
    * */
    public function out($content)
    {
        if(is_array($content)|is_object($content))
        {
            print_r($content);
        }
        else 
        {
            echo $content;
        } 
    }
   /**
   * 返回指定文件夹的文件个数
   *  
   * @param mixed $path  指定的路径
   * @return int 返回指定文件夹的文件个数
   */
    public function fileCount($path)
    {
      return  count(glob($path."/*.*"));
    }
    
    /**
    * @desc 对session操作的封装
    * 
    * @param mixed $key 健
    * @param mixed $value  值
    * @return mixed 设置或取值
    */
    public function session($key,$value="")
    {
        if(!isset($_SESSION))
        {
        session_start();
        } 
        if($value=="")
        {
            if(isset($_SESSION[$key]))
            {
                return $_SESSION[$key];
            }
            else
            {
                return null;
            }
        } else
        {
            if($value==null)
            {
             session_unset($_SESSION[$key]);   
            }
            else
            {
            $_SESSION[$key]=$value;
            }
        }
    }
    /**
    *  验证指定字符串是否符合某种格式
    * 
    * @param mixed $str  待验证的字符串
    * @param mixed $rule  验证规则
    * @param mixed $message  验证不通过时显示的信息
    * @param mixed $isExit   验证不通过时，是否终止运行
    * @param mixed $ajax   是否是Ajax请求
    */
    function checkData($str,$rule,$message,$isExit=1,$ajax=1)
    {
         if($this->test($rule,"function\:\w+"))
         {
             $func= preg_split('/:/',$rule);
             if(function_exists($func[1]))
             {      
                if(!(isset($func[3])?$func[1]($str,$func[2],$func[3]):(isset($func[2])?$func[1]($str,$func[2]):$func[1]($str))))
                {
                  $this->error($message,$ajax);
                   if($isExit) $this->end();   
                }
                else
                {   
                   // if($isExit) $this->end(); 
                    return ;
                }
             }
         }
         if(!$this->test($str,$rule))
         {
             $this->error($message,$ajax);
             if($isExit) $this->end();
         }
    }
    /**
    * 上传文件的检查
    * 
    * @param mixed $file_ext 文件的扩展名,用|分隔
    * @param mixed $file_size  上传文件的大小,单位KB
    * @param mixed $ajax   返回值是否为Ajax
    */
    function checkUpload($file_ext='',$file_size=0,$ajax=1)
    {
        $exts=explode("|",strtolower($file_ext));
        
        if($file_ext=="")
        {
            $file_ext=$this->C("");
        }
        if($file_size==0)
        {
            $file_size=$this->C("file_size");
        }
       // $this->error(($_FILES['file2']['error']),1);
        //return ;
        foreach ($_FILES as $file=>$content)
        {
            if($content["error"])
            { 
                $this->error("上传文件有误,或上传文件为空",1);
                return false;
            }
            if(ceil($content["size"]/1024)>$file_size)
            {
            $this->error("上传文件过大",$ajax);
            return false;
            }
            if($file_ext!="*")
            {  $i=0;
                for($i=0;$i<count($exts);$i++)
                {
                    $ex=explode(".",strtolower($content["name"]));
                    if(count($ex)>1)
                    $ext=$ex[count($ex)-1];
                    else
                    $ext="";
                    if(($exts[$i]==$ext))
                    {
                      // $this->error($ext,$ajax);  
                      // return false; 
                        break;
                    }
                    if($i>=(count($exts)-1))
                    {
                          $this->error("上传文件格式不对",$ajax);
                         //$this->error($exts[$i],$ajax);
                        return false;
                    }
                }
            }
        }
        return true;
    }
    
    /**
    * 文件上传
    * 
    * @param mixed $path 文件上传的路径
    * @return 返回上传后的文件信息，此信息为一个二维数组
    */
    function upload($path)
    {
        $files=array();
        foreach ($_FILES as $file=>$content)
        {
            $ext=explode(".",strtolower($content["name"]));
            if(count($ext)>1)
            $ext=$ext[count($ext)-1];
            $files[$file]["name"] =date('Ymd-').rand(time(),time()+100).".".$ext;
            $files[$file]["type"] = $ext;
            $files[$file]["error"] = $content["error"];
            $files[$file]["size"] =$content["size"];
            $files[$file]["path"] =$path;
            move_uploaded_file($content["tmp_name"],$path."".$files[$file]["name"]);
        }
       return $files;
    }
    
    /**
 * 发送文件
 *
 * @param string   $fileName      文件名称或路径
 * @param string   $fancyName     自定义的文件名,为空则使用filename
 * @param boolean  $forceDownload 是否强制下载
 * @param integer  $speedLimit    速度限制,单位为字节,0为不限制,不支持windows服务器
 * @param string   $$contentType  文件类型,默认为application/octet-stream
 *
 * @return boolean
 */
    function sendFile($fileName, $fancyName = '', $forceDownload = true, $speedLimit = 0, $contentType = '')
{
    if (!is_readable($fileName))
    {
        header("HTTP/1.1 404 Not Found");
        return false;
    }

    $fileStat = stat($fileName);
    $lastModified = $fileStat['mtime'];
    
    $md5 = md5($fileStat['mtime'] .'='. $fileStat['ino'] .'='. $fileStat['size']);
    $etag = '"' . $md5 . '-' . crc32($md5) . '"';

    header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT');
    header("ETag: $etag");
    
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified)
    {
        header("HTTP/1.1 304 Not Modified");
        return true;
    }

    if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) < $lastModified)
    {
        header("HTTP/1.1 304 Not Modified");
        return true;
    }

    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&  $_SERVER['HTTP_IF_NONE_MATCH'] == $etag)
    {
        header("HTTP/1.1 304 Not Modified");
        return true;
    }

    if ($fancyName == '')
    {
        $fancyName = basename($fileName);
    }
    
    if ($contentType == '')
    {
        $contentType = 'application/octet-stream';
    }

    $fileSize = $fileStat['size'];   
    
    $contentLength = $fileSize;
    $isPartial = false;

    if (isset($_SERVER['HTTP_RANGE']))
    {
        if (preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches))
        {    
            $startPos = $matches[1];
            $endPos = $matches[2];

            if ($startPos == '' && $endPos == '')
            {
                return false;
            }
            
            if ($startPos == '')
            {
                $startPos = $fileSize - $endPos;
                $endPos = $fileSize - 1;
            }
            else if ($endPos == '')
            {
                $endPos = $fileSize - 1;
            }

            $startPos = $startPos < 0 ? 0 : $startPos;
            $endPos = $endPos > $fileSize - 1 ? $fileSize - 1 : $endPos;

            $length = $endPos - $startPos + 1;

            if ($length < 0)
            {
                return false;
            }

            $contentLength = $length;
            $isPartial = true;
        }
    }
    
    // send headers
    if ($isPartial)
    {
        header('HTTP/1.1 206 Partial Content');
        header("Content-Range: bytes $startPos-$endPos/$fileSize");
        
    }
    else
    {
        header("HTTP/1.1 200 OK");
        $startPos = 0;
        $endPos = $contentLength - 1;
    }

    header('Pragma: cache');
    header('Cache-Control: public, must-revalidate, max-age=0');
    header('Accept-Ranges: bytes');
    header('Content-type: ' . $contentType);
    header('Content-Length: ' . $contentLength);
    
    if ($forceDownload)
    {
        header('Content-Disposition: attachment; filename="' . rawurlencode($fancyName). '"');
    }

    header("Content-Transfer-Encoding: binary");
    
    $bufferSize = 2048;

    if ($speedLimit != 0)
    {
        $packetTime = floor($bufferSize * 1000000 / $speedLimit);
    }

    $bytesSent = 0;
    $fp = fopen($fileName, "rb");
    fseek($fp, $startPos);

    //fpassthru($fp);
    
    while ($bytesSent < $contentLength && !feof($fp) && connection_status() == 0 )
    {
        if ($speedLimit != 0)
        {
            list($usec, $sec) = explode(" ", microtime()); 
            $outputTimeStart = ((float)$usec + (float)$sec);
        }

        $readBufferSize = $contentLength - $bytesSent < $bufferSize ? $contentLength - $bytesSent : $bufferSize;
        $buffer = fread($fp, $readBufferSize);        

        echo $buffer;

        if(strpos("win", strtolower(PHP_OS))>0)
        ob_flush();
        flush();

        $bytesSent += $readBufferSize;
        
        if ($speedLimit != 0)
        {
            list($usec, $sec) = explode(" ", microtime()); 
            $outputTimeEnd = ((float)$usec + (float)$sec);
            
            $useTime = ((float) $outputTimeEnd - (float) $outputTimeStart) * 1000000;
            $sleepTime = round($packetTime - $useTime);
            if ($sleepTime > 0)
            {
                usleep($sleepTime);
            }
        }
    }
    

    return true;
}




    
    /**
    *浏览器友好的变量输出
    * */
    function dump($var, $echo=true,$label=null, $strict=true)
    {
        $label = ($label===null) ? '' : rtrim($label) . ' ';
        if(!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
            } else {
                $output = $label . " : " . print_r($var, true);
            }
        }else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if(!extension_loaded('xdebug')) {
                $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
                $output = '<pre>'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
            }
        }
        if ($echo) {
            echo($output);
            return null;
        }else
            return $output;
    }
    /**
    *取远程文件
    * 
    * <pre>
    * $easy->getcontent("http://www.baidu.com");//获取百度首页源代码
    * </pre>
    * */
    
    public function getcontent($url)
    {
        return file_get_contents($url);
    }
    /**
    *
    * 安全字符串
    * 
    * 将单引号就成双个单引号 ,内部实现  return preg_replace("/\'/","''",$str);  
    *  <pre>
    * $easy->safestr("i'm a student");//输出 i''m a student;
    * </pre>
    * */
    public function safestr($str)
    {
        
        return mysql_escape_string($str);
       //return preg_replace("/\'/","''",$str);
    }
     /**
     *
     * 初始化 POST或Get方式传递参数
     * 
     * 统一处理网页提交过来的数据,以便用统一的方法调用
     * */
    public function initParas()
    {
       if(count($_POST)>0) 
        foreach ($_POST as $key => $value) 
        {  
           //$this->paras[strtolower($key)]=addslashes($value); 
           $this->paras[strtolower($key)]=($value); 
        } 
        if(count($_GET)>0) 
        foreach ($_GET as $key => $value)
         { 
           // $this->paras[strtolower($key)]=addslashes($value); 
            $this->paras[strtolower($key)]=($value); 
        }
        return $this->paras;
    }
    /**
    *取得参数
    * 
    * 获取网页提交的参数    $easy->P("name") 等价于 $_POST["name"] 或 $_GET["name"];
    * <pre>
    *   $easy->P("name"); //取得name参数的值
    * </pre>
    * */
    public function P($paraName)
    {
        if(isset($this->paras[$paraName]))
        return $this->paras[$paraName];
        else
        return null;
    }
    /**
    *
    * 生成查询语句
    * 
    * 生成相应有SQL语句  
    * 
    * @param $table string 数据表名称
    * @param $valuelist array 字段值对应数组
    * @param $mode int  0-插入,  1-更新 ,2-删除,3-查询
    * <pre>
    *      $easy->buildSQL("test",array("title"=>"标题","content"=>"内容"),0);
    *     //返回  insert into test(title,content) values('标题','内容');
    * </pre>
    * 
    * */
    public function buildSQL($table,$valuelist,$mode=0)
    {
         $f="";$v="";
           switch ($mode) 
           {
              case 0: //生成插入语句             
                   if(is_array($valuelist))
                  { 
                   if(array_key_exists("0",$valuelist)) 
                   { 
                      foreach ($valuelist as $value) {
                       $value=$this->safestr($value);   
                       $f.= $this->substring($value,0,strpos($value,":")).",";
                       $v.="'".substr($value, strpos($value,":")+1,strlen($value))."',";  
                      }
                   }
                   else
                   {   
                     foreach ($valuelist as $key => $value) 
                     {
                        $value=$this->safestr($value);  
                        $f.=$key.",";
                        $v.="'".$value."',";
                     }    
                   }   

                  }
                  else
                  {
                      return "";
                  }
                 $f= substr( $f,0,strlen($f)-1);  
                 $v= substr( $v,0,strlen($v)-1); 
                 return  "insert into $table (".$f.") values(".$v.")";
                 break;
              case 1: //生成更新语句  
                  if(is_array($valuelist))
                  { 
                      if(array_key_exists("0",$valuelist))
                      {
                       foreach ($valuelist as $value) 
                       {
                           $value=$this->safestr($value);   
                           $f= $this->substring($value,0,strpos($value,":"));
                           $v=substr($value, strpos($value,":")+1,strlen($value)); 
                           $sql.=$f."='".$v."',";    
                       }    
                      }
                      else
                      {
                          $sql="";
                       foreach($valuelist as $key => $value)
                       {   
                           $value=$this->safestr($value);  
                           $sql.=$key."='".$value."',";
                       }
                      }
                   }
                      
                 
                    return "update $table set ".substr($sql,0,strlen($sql)-1); 
           
                break;
              case 2:    //生成删除语句
              
                return "delete from $table where ";
           
                break;
               case 3:    //生成查询语句
              
                return "select $valuelist from $table where ";
           
                break;
           }

        
    }
    /**
    *
    * 历遍数组
    * 
    * 通过回调函数历历遍数组和array_walk用法一致
    * 
    * <pre>
    *   
    *    function shownews($row)
    *    {
    *      print_r($row);//输出新闻
    *    }
    *    
    *   $news=$easy->db->query2array("select * from news"); //取得新闻数组
    * 
    *   $easy->each($news,"shownews");//历遍新闻数组
    *   
    * </pre>
    * 
    * @param $arr array 要历遍的数组
    * @param $fn string 回调函数的函数名
    * @param $para mixed 附加参数
    * 
    * */
    function each($arr,$fn,$para=null)
    {
        if(function_exists($fn))
        {
           foreach($arr as $item)
           {
               if($para!=null)
               $fn($item,$para);
               else
               $fn($item);
           }
           
        }
        else
        {
            $this->log( "Function '$fn' is not found!",$this->C("log_type"));
            $this->end();
        }
    }
    /**
    *
    * 弹出提示
    * 
    * @param $msg string 提示内容
    * @param $go int 前进或后 <script>alert('$msg');history.go($go);</script>
    * 
    * <pre>
    * $easy->alert("提交成功",0);//输出提示
    * </pre>
    * */
    function alert($msg,$go=-1)
    {   $go=($go==0)?-1:-1;
        $this->out("<script>alert('$msg');history.go($go);</script>");
    }
    /**
    *
    * 序列化并压缩数据 
    * 
    * @param $str mixed 要序列化的数据
    * @param $zip bool 是否压缩
    * @param $base64 是否使用base64编码
    * <pre>
    *      $easy->serialize($easy->db->query2array("select * from news"));//序列化新闻数组
    * </pre>
    * */  
    public function serialize($str,$zip=true,$base64=true)
    {
       if(($str=="")||($str==null)) 
       {
       return $str;
       }
       else
       {  
          $zip=function_exists('gzcompress')?$zip:false;
          if($zip&&$base64)
           {
            return  base64_encode(gzcompress(serialize($str)));
           }
           else if ($zip)
           {
               return gzcompress(serialize($str)); 
           }
           else if ($base64)
           {
              return  base64_encode((serialize($str))); 
           }
           else
           {
               return serialize($str);
           }
       }
    }
    /**
    *
    * 反序列化并解压缩数据
    * 
    * @param $str mixed 要序列化的数据
    * @param $zip bool 是否压缩
    * @param $base64 是否使用base64编码
    * <pre>
    *     $news= $easy->serialize($easy->db->query2array("select * from news"));//序列化新闻数组 
    *      $easy->unserialize($news);//返序列化新闻数组
    * </pre>
    * */  
    public function unserialize($str,$zip=true,$base64=true)
    {
       if(($str=="")||($str==null)) 
       {
       return $str;
       }
       else
       {
           $zip=function_exists('gzcompress')?$zip:false;
           if($zip&&$base64)
           {
            return unserialize(gzuncompress(base64_decode($str)));
           }
           else if ($zip)
           {    
               return  unserialize(gzuncompress(($str))); 
           }
           else if ($base64)
           {
              return unserialize((base64_decode($str))); 
           }
           else
           {
             return unserialize($str);
           }
       }
    }
    
            /**
        * @desc 向服务器发送数
        * 
        * @param $host String 主机名称
        * @param $path String 处理的URL
        * @param $data String POST的参数
        * @param $port int 远程主机的端口,默认80
        * 
        * <pre>
        *       $easy->post("www.abc.com","news/index.php","username=abc&pwd=abc");
        * </pre>
        */
       public function post($host,$path,$data,$port=80)
        {
            $fp = fsockopen($host, $port);
            fputs($fp,"POST $path HTTP/1.1\r\n");
            fputs($fp,"Host: $host\r\n");
            fputs($fp,"Content-type: application/x-www-form-urlencoded\r\n");
            fputs($fp,"Content-length: " . strlen($data) . "\r\n");
            fputs($fp, "User-Agent: MSIE\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $data);
            $buf='';
            while (!feof($fp)) 
            {
                $buf .= fgets($fp,128);
            }
            fclose($fp);
            preg_match_all("/HTTP\/1.1[\s\S]*?Content-Length:\s\d*\r\n\r\n([\s\S]*)/",$buf,$arr);
            if(count($arr)>0)
            {
              return $arr[1][0]?$arr[1][0]:$arr[1];
            }
            else
            {
                return "";
            } 
        } 
        
         /**
         * @desc 返回两个时间的时间差  $date1-$date2
         * @param $date1 String 时间1 
         * @param $date2 String 时间2
         * @param $unit String  时间差单位 s:秒 i:分钟 h:小时 d:日
         * @return 返回相时间的差
         */
        function datediff($date1, $date2, $unit = "")
         { //时间比较函数，返回两个日期相差几秒、几分钟、几小时或几天
            switch ($unit) 
            {
                case 's':
                     $dividend = 1;
                break;
                case 'i':
                     $dividend = 60;
                break;
                case 'h':
                     $dividend = 3600;
                break;
                case 'd':
                     $dividend = 86400;
                break;
                case 'm':
                     $dividend=2592000;
                     break;
                case 'y':
                     $dividend=31536000;
                     break;
                     default:
                $dividend = 86400;
            }
            if(!is_numeric($date1))
            $time1 = strtotime($date1);
             if(!is_numeric($date2)) 
            $time2 = strtotime($date2);
            if ($time1 && $time2)
            return ceil( (float)($time1 - $time2) / $dividend);
            return false;
        }
        
        /**
        * @desc 与当前时间比较时间的流逝
        * @param 要比较的日期
        * @return 返回时间流逝的表示
        */
        function passtime($date)
        {
          $res="";
          $currentTime=date('Y-m-d h:i:s');
          $seconds=  $this->datediff($currentTime,$date,"s");
          if($seconds>0)
          {
          if($seconds<60)
          return "刚刚";  
          $minutes=  $this->datediff($currentTime,$date,"i"); 
          if($minutes<60)
          return $minutes."分钟前";  
          $hours=   $this->datediff($currentTime,$date,"h"); 
          if($hours<24)
          return  $hours."小时前";
          $days=   $this->datediff($currentTime,$date,"d");
          if($days<30)
          return  $days."日前"; 
          $months=   $this->datediff($currentTime,$date,"m");  
          if($months<12)
          return  $months."月前"; 
           $years=   $this->datediff($currentTime,$date,"y");  
         // if($years<12)
          return  $years."年前";
          }
          else
          {
            $seconds= abs($this->datediff($currentTime,$date,"s")); 
          if($seconds<60)
          return "马上";  
          $minutes=  abs($this->datediff($currentTime,$date,"i")); 
          if($minutes<60)
          return $minutes."分钟后";  
          $hours=   abs($this->datediff($currentTime,$date,"h")); 
          if($hours<24)
          return  $hours."小时后";
          $days=   abs($this->datediff($currentTime,$date,"d"));
          if($days<30)
          return  $days."日后"; 
          $months=   abs($this->datediff($currentTime,$date,"m"));  
          if($months<12)
          return  $months."月后"; 
           $years=   abs($this->datediff($currentTime,$date,"y"));  
         // if($years<12)
          return  abs($years)."年后";
          }      
        }
        
       /**
       * @desc 将过滤参数字符串中的所有HTML标签，返回纯文本。 
       * @param $str 待过滤字符串 
       * @return 返回过滤后的字符串
       */
       function htmlFilter($str)
       {
        $str = preg_replace("/<[^>]+>/","",$str);
        $str = preg_replace("/>/", "&gt;",$str);
        $str = preg_replace("/</", "&lt;",$str);
        return $str;
       }
       
       /**
       * @desc 根据正则表达式验证数据合法性。
       * @param $str 待验证的字符串 
       * @pattern 正则表达式
       *                "date" - 验证是否为合法的日期格式 
                        "idcard" - 验证是否为合法的身份证号码 
                        "english" - 验证是否只包含英文字母 
                        "chinese" - 验证是否只包含中文字符 
                        "username" - 验证是否是合法的用户名（4-20位，只能是大小写字母数字及下划线且以字母开头） 
                        "email" - 验证是否是合法的E-mail地址 
                        "int" - 验证是否为整数 
                        "number" - 验证是否为数字 
                        "double" - 验证是否为双精度数字 
                        "price" - 验证是否为价格格式 
                        "zip" - 验证是否为合法的邮编 
                        "qq" - 验证是否为合法的QQ号 
                        "phone" - 验证是否为合法的电话号码 
                        "mobile" - 验证是否为合法的手机号码 
                        "url" - 验证是否为合法的URL地址 
                        "ip" - 验证是否为合法的IP地址 
       * @return 真或假
       */
       function test($str,$pattern)
       {
           switch ($pattern) 
           {
            case "date": return strtotime($str)?true:false;break;
            case "notnull":      $pattern   ='^$';$str=trim($str); if(strlen($str)==0) return 0; else return 1;break;
            case "idcard":       $pattern = '^(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|8[12]|91)\d{2}[01238]\d{1}$'         ;break; 
            case "english":      $pattern = '^[A-Za-z]+$';break;  
            case "chinese":      $pattern = '^[\u0391-\uFFE5]+$';break; 
            case "username":     $pattern = '^[a-z]\w{2,19}$'   ;break; 
            case "email":        $pattern = '^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$';break; 
            case "int":          $pattern = '^[-\+]?\d+$' ;break; 
            case "number":       $pattern = '^\d+$'   ;break; 
            case "double":       $pattern = '^[-\+]?\d+(\.\d+)?$'  ;break; 
            case "price":        $pattern = '^\d+(\.\d+)?$'    ;break; 
            case "zip":          $pattern = '^[1-9]\d{5}$'  ;break; 
            case "qq":           $pattern = '^[1-9]\d{4,9}$'    ;break; 
            case "phone":        $pattern = '^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$'  ;break; 
            case "mobile":       $pattern = '^((\(\d{2,3}\))|(\d{3}\-))?(1[35][0-9]|189)\d{8}$' ;break; 
            case "url":          $pattern = '^(http|https|ftp):\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\""])*$'  ;break; 
            case "domain":       $pattern = '^[A-Za-z0-9\-]+\.([A-Za-z]{2,4}|[A-Za-z]{2,4}\.[A-Za-z]{2})$'   ;break; 
            case "ip":           $pattern = '^(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5])$' ;break;   
           }
          return preg_match("/". $pattern."/", $str)>0?true:false;
       }
       /**
       * @desc 取得URL
       */
       function getUrl()
       {
          
           if($_SERVER['REQUEST_URI']=="")
            {
                 return  $REFERERURL=$_SERVER['HTTP_REFERER'];     
            }
            else
            {
                 return  $REFERERURL=$_SERVER['REQUEST_URI']; 
                 
            }
       }
       
         /**
     * @desc 生成随机字符串
     *  * @param $type 字符类型   1.字母与数字 alnum   2.字母 alpha 3.数字 numeric 4.非零数字 nozero
     * @param $len 生成随机字符串的长度
     * @return 生成的随机字符串
     */  
       function rndString($type = 'alnum', $len = 8)
    {                    
        switch($type)
        {
            case 'alnum'    :
            case 'numeric'    :
            case 'nozero'    :
            case 'alpha':
        
                    switch ($type)
                    {
                        
                        case 'alnum'    :    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            break;
                        case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            break;
                        case 'numeric'    :    $pool = '0123456789';
                            break;
                        case 'nozero'    :    $pool = '123456789';
                            break;
                    }

                    $str = '';
                    for ($i=0; $i < $len; $i++)
                    {
                        $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
                    }
                    return $str;
              break;
            case 'unique' : return md5(uniqid(mt_rand()));
              break;
        }
    }
     /**
     * @desc 生成验证码
     * @param $len 生成验证码的长度
     * @param $type 验证码使用的字符类型   1.字母与数字 alnum   2.字母 alpha 3.数字 numeric 4.非零数字 nozero
     * @return 生成的图片文件
     */
    function validCode($len,$name="valid_code",$type='alpha')
    {
       $checkcode= $this->rndString($type,$len); 
        if(!isset($_SESSION))
        {
        session_start();
        } 
        $_SESSION[$name]=$checkcode;
        $im = imagecreate(12*$len, 20);
        $bg = imagecolorallocate($im,150, 150, 150);
        $textcolor = imagecolorallocate($im, 0, 0, 0);
        imagestring($im, 5, 8, 2, $checkcode, $textcolor);
        header("Content-type: image/png");
        imagepng($im);
    }
    /**
    * @desc 使脚本停止往下执行
    */
    function end()
    {
       exit(0); 
    }
    
    /**
    * @desc 检查数据来源是否站内
    */
    function isOutPost()
    {            
        $servername=$_SERVER['SERVER_NAME'];
        if(isset($_SERVER["HTTP_REFERER"]))
        {
        $sub_from=$_SERVER["HTTP_REFERER"];
        }
        else
        {
            return false;
        }
        $sub_len=strlen($servername);
        $checkfrom=substr($sub_from,7,$sub_len);
        if($checkfrom!=$servername)
        {
             return true;
        }else
        {
            return false;
        } 
        
    }
    /**
    * @desc 置强制页面不保存在浏览器的缓存中。 
    */
    function noCache()
    {
     header ("Cache-Control: no-cache, must-ridate");
     header ("Pragma: no-cache");
    }
    
    /**
    * @desc 设置页面的字符集
    * @return 无返回值
    */
    function pageCharset($charset)
    {
      header("content-type:text/html; charset=$charset"); 
    }
    
    /**
    * 分页函数
    * 
    * @param mixed $url        超链接URL
    * @param mixed $total     总页数
    * @param mixed $pageid    第几页
    * @param mixed $pagename  分页参数名
    * @param mixed $psize 页大小
    * @param mixed $half   前后显示数
    */
    
    function page($url,$total,$pageid=1,$pagename='p',$psize=10,$half=3){
//分页函数,$total=总共的条数;${$pagename}=当前显示的页号;$psize=每页显示的条数;$half=$pageid前后显示的条数
    $totalpage=ceil($total/$psize);//总共的页数
    $i=0;
    $arr=array();
    $rand=rand(10,30);
    if($totalpage<2){//小于2页，不显示分页
        return;
    }
    if($pageid>1){//最前面几个
        $arr[$i]["msg"]="上一页";
        $arr[$i]["url"]=$url."?{$pagename}=".($pageid-1)."&id=".$rand;
        $i++;
        $arr[$i]["msg"]=1;
        $arr[$i]["url"]=$url."?{$pagename}=1&id=".$rand;
        if($pageid-$half>2){//是否显示  ...
            $i++;
            $arr[$i]["msg"]="...";
        }
        $i++;/**/
    }

    for($j=0;$j<$half;$j++,$i++){//$pageid前面的[最多$half个]
        if($pageid-$half+$j<2){//
            $i--;//使$i保持不变
            continue;
        }/**/
        $arr[$i]["msg"]=$pageid-$half+$j;
        $arr[$i]["url"]=$url."?{$pagename}=".($pageid-$half+$j)."&id=".$rand;
    }
    
    {//中间项
        $arr[$i]["msg"]="[".$pageid."]";
        $arr[$i]["url"]=$url."?{$pagename}=".($pageid)."&id=".$rand;
        $i++;
    }
    
    for($j=0;$j<$half;$j++,$i++){//$pageid后面的[最多($half-1)个]
        if($pageid+$j+1>$totalpage){//
            $i++;
            break;
        }
        $arr[$i]["msg"]=$pageid+$j+1;
        $arr[$i]["url"]=$url."?{$pagename}=".($pageid+$j+1)."&id=".$rand;
    }
    if($pageid+$half+1<$totalpage){//最后一页，有省略号
        $arr[$i]["msg"]="...";
        $i++;
        $arr[$i]["msg"]=$totalpage;
        $arr[$i]["url"]=$url."?{$pagename}=".($totalpage)."&id=".$rand;
        $i++;
    }
    if($pageid+$half+1==$totalpage){//最后一页,无省略号
        $arr[$i]["msg"]=$totalpage;
        $arr[$i]["url"]=$url."?{$pagename}=".($totalpage)."&id=".$rand;
        $i++;
    }
    if($pageid!=$totalpage){//是否显示下一页
        $arr[$i]["msg"]="下一页";
        $arr[$i]["url"]=$url."?{$pagename}=".($pageid+1)."&id=".$rand;    
    }
    
    $msg="<div><span>共".$total."条</span>&nbsp;";
    foreach($arr as $value ){//转为html
        if(strcmp("...",$value["msg"])==0){
            $msg.=$value["msg"]."&nbsp;";            
        }
        else{
            $msg.="<span><a href=\"".$value["url"]."\">".$value["msg"]."</a></span>&nbsp;";
        }
    }
    return $msg."</div>";
}

    function pagerReturn($data,$url,$total,$pageid=1,$pagename='p',$psize=10,$half=3)
    {
       $result["list"]=$data;
       $result["page_count"]=$total;
        if(!$pageid) $pageid=1;
       $result["page"]=ceil( $pageid/10);
       $result["pager"]= $this->page($url,$total,$pageid,$pagename,$psize,$half);
       $this->ajaxReturn($result,'分页',1);
    }
    
    
    function getSessionId()
    {
         if(!isset($_SESSION))
        {
        session_start();
        } 
       return session_id(); 
    }
    
    /**
    * @desc 输出json的信息,以供ajax调用
    * @param $data 返回值
    * @param $message 显示的信息
    * @return 无返回值,直接输出内容
    */
    
     function ajaxReturn($data,$info='',$status=1,$type='')
    {
        $result  =  array();
        $result['status']  =  $status;
        $result['info'] =  $info;
        $result['data'] = $data;
        $result["PHPSESSID"]=$this->getSessionId();
        if(empty($type)) $type  =   $this->C('ajax_return_type');
        if(strtoupper($type)=='JSON') {
            // 返回JSON数据格式到客户端 包含状态信息
          //  header("Content-Type:text/html; charset=utf-8");
           // exit(json_encode($result));
          $this->out( $this->jsonEncode($result));  
          $this->end();
        }elseif(strtoupper($type)=='XML'){
            // 返回xml格式数据
            //header("Content-Type:text/xml; charset=utf-8");
           // exit(xml_encode($result));
          $this->out( $this->jsonEncode($result));
           $this->end();   
        }elseif(strtoupper($type)=='EVAL'){
            // 返回可执行的js脚本
            //header("Content-Type:text/html; charset=utf-8");
           // exit($data);
          $this->out( $this->jsonEncode($result)); 
          $this->end();
        }else{
            // TODO 增加其它格式
        }
    }
    
     /**
     * @desc 操作成功信息提示
     * @param $message 成功信息提示 
     *   
     */
     function success($message,$ajax=false)
    {
       return $ajax?$this->ajaxReturn('',$message,1):1;      
    }
    
    /**
    * @desc 操作出错信息提示
    * @param $message 错误信息
    * 
    */
    
     public function actionPath($path) {
       // $this->path = $path;
       $this->C(array("action_path"=>$path));
    }
    
    function error($message,$ajax=false)
    {
      return $ajax?$this->ajaxReturn('',$message,0):0;
    }

    
    
  /**
     * @desc 通过URL路由到指定的Action类中的方法
     * <pre>
     * 例如：url: http://127.0.0.1:8084/easyphplibrary/test.php/test/index/page/3/kind/5
     *   则路由到 TestAction.php 中的index方法 参数为 array("page"=>3,"kind"=>5)
     * </pre>
     * @return void
     * @access public
     *
     */
    public function route(){
        $path=$this->C("action_path");
        if (empty($path)) {
            $this->log("没有设置程序目录!",$this->C("log_type"));
        }
        $this->parsePath();
        $this->getActionFile();
        $this->getActionClass();
    }
    /**
     * 解析URL路径
     * 
     * @return void
     * @access private
     *
     */
    private function parsePath(){
        if( strpos($_SERVER["REQUEST_URI"],"?")>0)
        {
        list($path, $param) = explode("?", $_SERVER["REQUEST_URI"]);
        }
        else
        {
          $path= $param= $_SERVER["REQUEST_URI"];
        }
        $param = explode("/",str_replace($this->C("action_path"), '', $path));  
        $action_param=array();
        $action_param['module'] = isset($param[1])?$param[1]:null; 
        $action_param['action'] = isset($param[2])?$param[2]:null;       
        try{
        for ($i=3;$i<count($param);$i++)
         {
             $j=$i+1;
            if(isset($param[$j]))
            {
            $action_param[$param[$i]] = $param[++$i];
            }
            else
            {
                throw new  Exception("参数解释错误");
            }
        }
        }
        catch(Exception $e)
        {
           $this->log($e->getMessage(),$this->C("log_type"));
        }
        $this->C(array("action_param"=>$action_param));
    }

    /**
     * 根据解析的URL获取Action文件
     * 
     * @return void
     * @access private
     *
     */
    private function getActionFile(){
        $action_param=$this->C("action_param");
        $action_file= "./Action/".$action_param['module']."Action.php";   
        if(!file_exists($action_file)) {
            $this->log("错误的请求，找不到Action文件(".$action_file.")",$this->C("log_type"));
        } else {
            include_once($action_file);
        }
    }

    /**
     * 根据Action文件名获取Action类名并且执行
     * 
     * @return void
     * @access private
     *
     */
    private function getActionClass(){
        $action_param=$this->C("action_param");
        $action_class=$action_param['module']."Action";
        $this->C (array("action_class"=>$action_class));
        if(!class_exists($action_class)) {
            $this->log("错误的请求，找不到Action类(".$action_class.")",$this->C("log_type"));
        } else {
            $newAction = new $action_class();
            $newAction->$action_param["action"]($action_param,$this);
        }
    }
}//EasyPHP类结束

/**
*
* MySQL数据库操作类
* 
* */
class MySQL extends EasyPHP
  {
       private $con;//数据库连link
       private $db_port;//数据端口
       private $db_host;//数据库地址
       private $db_name;//数据库名称
       private $db_user;//数据库用户
       private $db_pwd; //数据库密码
       private $db_charset;//数据库字符集
       public  $sqls=array(); //记录最近100条sql语句
       
       private $tranSQLS=array();//记录事务SQL
       private $isTran=false;//是否开始事务
       //public  $cache;
      
       /**
       *
       * 开始事务
       * */ 
       public function startTran()
       {
          $this->isTran=true; 
          $this->query("SET AUTOCOMMIT=0");
       }
       /**
       *
       * 回事务
       * */ 
       public function rollback()
       {
           $this->isTran=false;
           $this->query("ROLLBACK");
           $this->query("SET AUTOCOMMIT=1"); 
       }
       /**
       *
       * 提交事务
       * 
       * */ 
       public function commitTran()
       {
         $this->isTran=false;  
         foreach ($this->tranSQLS as $value)
          {
            if( !$this->query($value))
            {
                $this->query("ROLLBACK");
                $this->query("SET AUTOCOMMIT=1");  
                break;
            }
          }
          $this->query("SET AUTOCOMMIT=1");
          
          $this->out($this->tranSQLS);
          
          while(array_pop($this->tranSQLS)); 
          $this->out($this->tranSQLS); 
       }
       /**
       *
       * 构造函数
       * 
       *  */  
       public function __construct($cfg=array())
       { 
        //echo "MySQL";   
        //$this->config($this->cfg);
        $this->config($cfg);
       }
       /**
       *
       * 查询SQL
       * 
       * */ 
       public function query($sql)
       {
          
           if($this->isTran)
           {
               array_push($this->tranSQLS,$sql);
               return;
           }  
           if(!$this->con)
          {
              $this->open();
          }  
           static $num;//记录SQL次数
           if($this->C("show_sql"))
           {
            if(!isset($num))$num=0;
            if($num>=100)
            {
              $num=0;
            }
            else
            {
             $num++;
            }    
            $this->sqls[$num]=array($num=>$sql);//记录SQL语句
           }
          $rs=mysql_query($sql,$this->con);
          if($rs)
          {
              return $rs;
          }
          else
          {  
             if($this->C("debug"))
             $this->out("SQL语句出错：".$sql);
             if(($this->C("log_type")==1)or($this->C("log_type")==2))
             $this->log2file($sql);
             $this->log("SQL语句出错".mysql_errno($this->con).":".mysql_error($this->con));   
          }
       }
       /**
       *
       * 查询结查到二维数据  数据带缓存
       * 
       * */ 
       public function query2array($sql,$iscache=true,$result_type=MYSQL_ASSOC)
       {
           if($this->C("cache_type")==0)
           {   //文件缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       //$this->cache->clear();     
                        if(!$this->cache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->cache->set($sql,$result);
                            return $result;
                          
                        }
                        else
                        {
						    if($this->cache->exist(($sql)))
						    {
                              return $this->cache->get($sql);
						    }
						    else
						    {
							      $rs=$this->query($sql); 
							      return  $this->rs2array($rs,$result_type); 
						    }
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
           } 
           else if($this->C("cache_type")==1)
           { //数据库缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       // $this->dbcache->clear();     
                        if(!$this->dbcache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->dbcache->set($sql,$result);
                            return $result;
                        }
                        else
                        {
                             $rs=$this->query($sql); 
                              return  $this->rs2array($rs,$result_type); 
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
               
           }
           else
           {
              $rs=$this->query($sql); 
              return  $this->rs2array($rs,$result_type); 
           } 

       }
           /**
           *
           * 数据库转数组
           * 
           * */ 
        function rs2array($rs,$result_type=MYSQL_BOTH)
        {
           if($rs)
           { 
           $result=array();
           $i=0;
           while($row=mysql_fetch_array($rs,$result_type))
           {
             $result[$i]=$row;
             $i=$i+1;  
           }
           return $result;
           }
           else
           {
               return null;
           }    
        }
       /**
       *执行Sql
       * 
       * */ 
       public function execute($sql)
       {
         return  $this->query($sql);
       }
       public function getfields($table)
       {
          return $this->query2array("show full fields from $table");
       }
       /**
       *插入数据
       * 
       * */ 
       public function insert($table,$valuelist=null)
       {
          //自动适应提交数据生成插语句，此时$valuelist可以不用传参
          $f="";
          $v="";
          if($valuelist==null)
          {
              $arr= $this->getfields($table);
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $f.=$arr[$i]["Field"].",";
                 $v.="'".$this->safestr($this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($f,strlen($f)-1,1)==",")
              $f=substr($f,0,strlen($f)-1);
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("insert int $table($f) values($v)"); 
          }
          else
          { 
           return  $this->query( $this->buildSQL($table,$valuelist,0));  
          }          
       }
       /**
       *
       * 更新数据
       * 
       * */ 
       public function update($table,$valuelist=null,$where="1=0")
       {   //如果$valuelist为空时，自动按表的结构和参数生成更新语句
           if($valuelist==null)
           { 
              $arr= $this->getfields($table);     
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $v.=$arr[$i]["Field"]."='".$this->safestr( $this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("update $table set $v where ".$where); 
           }
           else
           {
             return  $this->query( $this->buildSQL($table,$valuelist,1)." where ".$where); 
           }   
       }
       /**
       *
       * 删除数据
       * 
       * */ 
       public function delete($table,$where)
       {
           return $this->query($this->buildSQL($table,"",2)." $where");
       }
       public function select($table,$filels,$where)
       {
          return $this->query($this->buildSQL($table,$filels,3)." $where");  
       } 
       /**
       *
       * 返回首行首列
       * 
       * */   
       public function scalar($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=mysql_fetch_row($rs))
           {
               return $row[0];
           }
        }
        else
        {
            return null;
        }  
       }
       /**
       *
       * 返回首行
       * 
       * */ 
       public function scalarRow($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=mysql_fetch_array($rs,MYSQL_BOTH))
           {
               return $row;
           }
        }  
       }
       /**
       *
       * 数据库配置
       * 
       * */ 
       public function config($cfg)
       { 
           $this->cfg=array_merge($this->cfg,$cfg);
           $this->db_host=$this->cfg["db_host"];
           $this->db_port=$this->cfg["db_port"];
           $this->db_user=$this->cfg["db_user"];
           $this->db_name=$this->cfg["db_name"];
           $this->db_pwd=$this->cfg["db_pwd"];
           $this->db_charset=$this->cfg["db_charset"];    
       }
       /**
       *打开数据连接
       * 
       * */ 
       public function open()
       {
           $this->con= mysql_connect($this->db_host.":".$this->db_port,$this->db_user,$this->db_pwd);
           if(!$this->con)
           {
               $this->log("数据库连接出错".mysql_errno($this->con).mysql_error($this->con));
              // exit;
           }
           else
           {   
           mysql_select_db($this->db_name,$this->con);
           $this->query("set names ".$this->db_charset);
           }
           return;    
       }
       /**
       *
       * 关闭数据连接
       * 
       * */ 
       public function close()
       {
           if($this->con)
           mysql_close($this->con);
       }
  }//MySQL类结束
  
/**
* @desc MSSQL数据库操作类
*   
*/
class MSSQL extends EasyPHP
  {
       private $con;//数据库连link
       private $db_port;//数据端口
       private $db_host;//数据库地址
       private $db_name;//数据库名称
       private $db_user;//数据库用户
       private $db_pwd; //数据库密码
       private $db_charset;//数据库字符集
       public  $sqls=array(); //记录最近100条sql语句
       
       private $tranSQLS=array();//记录事务SQL
       private $isTran=false;//是否开始事务
       //public  $cache;
       
       
      
       /**
       *
       * 开始事务
       * 
       * */ 
       public function startTran()
       {
          $this->query("BEGIN TRANSACTION DEPS02_DEL");
          $this->isTran=true; 
       }
       /**
       *
       * 回事务
       * 
       * */ 
       public function rollback()
       {
           $this->isTran=false;
           $this->query("ROLLBACK TRANSACTION DEPS02_DEL");
       }
       /**
       *
       * 提交事务
       * 
       * */ 
       public function commitTran()
       {
         $this->isTran=false;  
         foreach ($this->tranSQLS as $value)
          {
            if( !$this->query($value))
            {
                $this->query("ROLLBACK TRANSACTION DEPS02_DEL");
                $this->query("COMMIT TRANSACTION DEPS02_DEL");  
                break;
            }
          }
          $this->query("COMMIT TRANSACTION DEPS02_DEL");
          
          $this->out($this->tranSQLS);
          
          while(array_pop($this->tranSQLS)); 
          $this->out($this->tranSQLS); 
       }
       /**
       *
       * 构造函数
       * 
       *  */  
       public function __construct()
       { 
        //echo "MySQL";   
        $this->config($this->cfg);
       }
       /**
       *
       * 查询SQL
       * 
       * */ 
       public function query($sql)
       {
          
           if($this->isTran)
           {
               array_push($this->tranSQLS,$sql);
               return;
           }  
           if(!$this->con)
          {
              $this->open();
          }  
           static $num;//记录SQL次数
           if($this->C("show_sql"))
           {
            if(!isset($num))$num=0;
            if($num>=100)
            {
              $num=0;
            }
            else
            {
             $num++;
            }    
            $this->sqls[$num]=array($num=>$sql);//记录SQL语句
           }
          $rs=mssql_query($sql,$this->con);
          if($rs)
          {
              return $rs;
          }
          else
          {  
             if($this->C("debug"))
             $this->out("SQL语句出错：".$sql);
             if(($this->C("log_type")==1)or($this->C("log_type")==2))
             $this->log2file($sql);
            // $this->log("SQL语句出错".mssql_($this->con).":".mysql_error($this->con));   
          }
       }
       /**
       *
       * 查询结查到二维数据  数据带缓存
       * 
       * */ 
       public function query2array($sql,$iscache=true,$result_type=MSSQL_ASSOC)
       {   
           if($this->C("cache_type")==0)
           {   //文件缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       //$this->cache->clear();     
                        if(!$this->cache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->cache->set($sql,$result);
                            return $result;
                          
                        }
                        else
                        {
                            if($this->cache->exist(($sql)))
                            {
                              return $this->cache->get($sql);
                            }
                            else
                            {
                                  $rs=$this->query($sql); 
                                  return  $this->rs2array($rs,$result_type); 
                            }
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
           } 
           else if($this->C("cache_type")==1)
           { //数据库缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       // $this->dbcache->clear();     
                        if(!$this->dbcache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->dbcache->set($sql,$result);
                            return $result;
                        }
                        else
                        {
                             $rs=$this->query($sql); 
                              return  $this->rs2array($rs,$result_type); 
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
               
           }
           else
           {
              $rs=$this->query($sql); 
              return  $this->rs2array($rs,$result_type); 
           } 

       }
           /**
           *
           * 数据库转数组
           * 
           * */ 
        function rs2array($rs,$result_type=MYSQL_BOTH)
        {
           if($rs)
           { 
           $result=array();
           $i=0;
           while($row=mssql_fetch_array($rs,$result_type))
           {
             $result[$i]=$row;
             $i=$i+1;  
           }
           return $result;
           }
           else
           {
               return null;
           }    
        }
       /**
       *
       * 执行Sql
       * 
       * */ 
       public function execute($sql)
       {
         return  $this->query($sql);
       }
       public function getfields($table)
       {
          return $this->query2array("show full fields from $table");
       }
       /**
       *
       * 插入数据
       * 
       * */ 
       public function insert($table,$valuelist=null)
       {
          //自动适应提交数据生成插语句，此时$valuelist可以不用传参
          if($valuelist==null)
          {
              $arr= $this->getfields($table);
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $f.=$arr[$i]["Field"].",";
                 $v.="'".$this->safestr($this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($f,strlen($f)-1,1)==",")
              $f=substr($f,0,strlen($f)-1);
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("insert int $table($f) values($v)"); 
          }
          else
          { 
           return  $this->query( $this->buildSQL($table,$valuelist,0));  
          }          
       }
       /**
       *
       * 更新数据
       * 
       * */ 
       public function update($table,$valuelist=null,$where="1=0")
       {   //如果$valuelist为空时，自动按表的结构和参数生成更新语句
           if($valuelist==null)
           { 
              $arr= $this->getfields($table);     
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $v.=$arr[$i]["Field"]."='".$this->safestr( $this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("update $table set $v where ".$where); 
           }
           else
           {   
             return  $this->query( $this->buildSQL($table,$valuelist,1)." where ".$where); 
           }   
       }
       /**
       *
       * 删除数据
       * 
       * */ 
       public function delete($table,$where)
       {
           return $this->query($this->buildSQL($table,"",2)." $where");
       }
       public function select($table,$filels,$where)
       {
          return $this->query($this->buildSQL($table,$filels,3)." $where");  
       } 
       /**
       *
       * 返回首行首列
       * 
       * */   
       public function scalar($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=mssql_fetch_row($rs))
           {
               return $row[0];
           }
        }
        else
        {
            return null;
        }  
       }
       /**
       *
       * 返回首行
       * 
       * */ 
       public function scalarRow($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=mssql_fetch_array($rs,MSSQL_BOTH))
           {
               return $row;
           }
        }  
       }
       /**
       *
       * 数据库配置
       * 
       * */ 
       public function config($cfg)
       { 
           $this->cfg=array_merge($this->cfg,$cfg);
           $this->db_host=$this->cfg["db_host"];
           $this->db_port=$this->cfg["db_port"];
           $this->db_user=$this->cfg["db_user"];
           $this->db_name=$this->cfg["db_name"];
           $this->db_pwd=$this->cfg["db_pwd"];
           $this->db_charset=$this->cfg["db_charset"];    
       }
       /**
       *
       * 打开数据连接
       * 
       * */ 
       public function open()
       {
           $this->con= mssql_connect($this->db_host.",".$this->db_port,$this->db_user,$this->db_pwd);
         // $this->con=mssql_connect($this->db_host,$this->db_user,$this->db_pwd);
           if(!$this->con)
           {
               
               $this->log("数据库连接出错".mysql_errno($this->con).mysql_error($this->con));
              // exit;
           }
           else
           {   
           mssql_select_db($this->db_name,$this->con);
           //$this->query("set names ".$this->db_charset);
           }
           return;    
       }
       /**
       *
       * 关闭数据连接
       * 
       * */ 
       public function close()
       {
           if($this->con)
           mssql_close($this->con);
       }
  }//MSSQL类结束
/**
* @desc ODBC数据库操作类  
*/
  
      class ODBC extends EasyPHP
  {
       private $con;//数据库连link
       private $db_port;//数据端口
       private $db_host;//数据库地址
       private $db_name;//数据库名称
       private $db_user;//数据库用户
       private $db_pwd; //数据库密码
       private $db_charset;//数据库字符集
       public  $sqls=array(); //记录最近100条sql语句
       
       private $tranSQLS=array();//记录事务SQL
       private $isTran=false;//是否开始事务
       //public  $cache;
      
       /**
       *
       * 开始事务
       * */ 
       public function startTran()
       {
          $this->isTran=true; 
         // $this->query("SET AUTOCOMMIT=0");
         if(!$this->con)
         $this->open();
          odbc_autocommit($this->con,FALSE);
       }
       /**
       *
       * 回事务
       * 
       * */ 
       public function rollback()
       {
           $this->isTran=false;
           odbc_rollback($this->con); 
       }
       /**
       *
       * 提交事务
       * 
       * */ 
       public function commitTran()
       {
         $this->isTran=false;  
         foreach ($this->tranSQLS as $value)
          {
            if( !$this->query($value))
            {
                //$this->query("ROLLBACK");
                //$this->query("SET AUTOCOMMIT=1");  
                odbc_rollback($this->con);
                break;
            }
          }
         // $this->query("SET AUTOCOMMIT=1");
         odbc_commit($this->con);
          
          $this->out($this->tranSQLS);
          
          while(array_pop($this->tranSQLS)); 
          $this->out($this->tranSQLS); 
       }
       /**
       *
       * 构造函数 
       * 
       * */  
       public function __construct()
       { 
        //echo "MySQL";   
        $this->config($this->cfg);
       }
       /**
       *
       * 查询SQL
       * 
       * */ 
       public function query($sql)
       {
          
           if($this->isTran)
           {
               array_push($this->tranSQLS,$sql);
               return;
           }  
           if(!$this->con)
          {
              $this->open();
          }  
           static $num;//记录SQL次数
           if($this->C("show_sql"))
           {
            if(!isset($num))$num=0;
            if($num>=100)
            {
              $num=0;
            }
            else
            {
             $num++;
            }    
            $this->sqls[$num]=array($num=>$sql);//记录SQL语句
           }
          $rs=odbc_exec($this->con,$sql);
          if($rs)
          {
              return $rs;
          }
          else
          {  
             if($this->C("debug"))
             $this->out("SQL语句出错：".$sql);
             if(($this->C("log_type")==1)or($this->C("log_type")==2))
             $this->log2file($sql);
             $this->log("SQL语句出错".odbc_error($this->con).":".odbc_error($this->con));   
          }
       }
       /**
       *
       * 查询结查到二维数据  数据带缓存
       * 
       * */ 
       public function query2array($sql,$iscache=true,$result_type=MYSQL_ASSOC)
       {
           if($this->C("cache_type")==0)
           {   //文件缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       //$this->cache->clear();     
                        if(!$this->cache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->cache->set($sql,$result);
                            return $result;
                          
                        }
                        else
                        {
                            if($this->cache->exist(($sql)))
                            {
                              return $this->cache->get($sql);
                            }
                            else
                            {
                                  $rs=$this->query($sql); 
                                  return  $this->rs2array($rs,$result_type); 
                            }
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
           } 
           else if($this->C("cache_type")==1)
           { //数据库缓存
               if($this->C("cache_on"))
               { 
                   if($iscache)
                   {
                       // $this->dbcache->clear();     
                        if(!$this->dbcache->exist(($sql)))
                        {   
                            $rs=$this->query($sql); 
                            $result= $this->rs2array($rs,$result_type);
                            $this->dbcache->set($sql,$result);
                            return $result;
                        }
                        else
                        {
                             $rs=$this->query($sql); 
                              return  $this->rs2array($rs,$result_type); 
                        }
                   }
                   else
                   {
                      $rs=$this->query($sql); 
                      return  $this->rs2array($rs,$result_type);   
                   }
               } 
               else
               {   
                   $rs=$this->query($sql); 
                   return  $this->rs2array($rs,$result_type);  
               }
               
           }
           else
           {
              $rs=$this->query($sql); 
              return  $this->rs2array($rs,$result_type); 
           } 

       }
           /**
           *
           * 数据库转数组
           * 
           * 
           * */ 
        function rs2array($rs,$result_type=MYSQL_BOTH)
        {  
           if($rs)
           { 
           $result=array();
           $i=0;
           while($row=odbc_fetch_array($rs))    //这里作了修改
           {
             $result[$i]=$row;
             $i=$i+1;  
           }
           return $result;
           }
           else
           {
               return null;
           }    
        }
       /**
       *
       * 执行Sql
       * 
       * */ 
       public function execute($sql)
       {
         return  $this->query($sql);
       }
       public function getfields($table)
       {
          return $this->query2array("show full fields from $table");
       }
       /**
       *
       * 插入数据
       * 
       * */ 
       public function insert($table,$valuelist=null)
       {
          //自动适应提交数据生成插语句，此时$valuelist可以不用传参
          if($valuelist==null)
          {
              $arr= $this->getfields($table);
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $f.=$arr[$i]["Field"].",";
                 $v.="'".$this->safestr($this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($f,strlen($f)-1,1)==",")
              $f=substr($f,0,strlen($f)-1);
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("insert int $table($f) values($v)"); 
          }
          else
          { 
           return  $this->query( $this->buildSQL($table,$valuelist,0));  
          }          
       }
       /**
       *
       * 更新数据
       * 
       * */ 
       public function update($table,$valuelist=null,$where="1=0")
       {   //如果$valuelist为空时，自动按表的结构和参数生成更新语句
           if($valuelist==null)
           { 
              $arr= $this->getfields($table);     
              for($i=0;$i<count($arr);$i++)
              {
                 if($this->P(strtolower($arr[$i]["Field"])))
                 {
                 $v.=$arr[$i]["Field"]."='".$this->safestr( $this->P(strtolower($arr[$i]["Field"])))."',";
                 }  
              }
              if(substr($v,strlen($v)-1,1)==",")
              $v=substr($v,0,strlen($v)-1);
              return $this->query("update $table set $v where ".$where); 
           }
           else
           {
             return  $this->query( $this->buildSQL($table,$valuelist,1)." where ".$where); 
           }   
       }
       /**
       *
       * 删除数据
       * 
       * */ 
       public function delete($table,$where)
       {
           return $this->query($this->buildSQL($table,"",2)." $where");
       }
       public function select($table,$filels,$where)
       {
          return $this->query($this->buildSQL($table,$filels,3)." $where");  
       } 
       /**
       *
       * 返回首行首列
       * 
       * */   
       public function scalar($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=odbc_fetch_row($rs))
           {
               return $row[0];
           }
        }
        else
        {
            return null;
        }  
       }
       /**
       *
       * 返回首行
       * 
       * */ 
       public function scalarRow($sql)
       {
        if($rs=$this->query($sql))
        { 
           if($row=odbc_fetch_array($rs))
           {
               return $row;
           }
        }  
       }
       /**
       *
       * 数据库配置
       * 
       * */ 
       public function config($cfg)
       { 
           $this->cfg=array_merge($this->cfg,$cfg);
           $this->db_host=$this->cfg["db_host"];
           $this->db_port=$this->cfg["db_port"];
           $this->db_user=$this->cfg["db_user"];
           $this->db_name=$this->cfg["db_name"];
           $this->db_pwd=$this->cfg["db_pwd"];
           $this->db_charset=$this->cfg["db_charset"];    
       }
       /**
       *
       * 打开数据连接
       * 
       * */ 
       public function open()
       {
           $this->con= odbc_connect($this->db_host,$this->db_user,$this->db_pwd,SQL_CUR_USE_ODBC);
           if(!$this->con)
           {
               $this->log("数据库连接出错".odbc_error($this->con).odbc_error($this->con));
              // exit;
           }
           else
           {   
           //mysql_select_db($this->db_name,$this->con);
           //$this->query("set names ".$this->db_charset);
           }
           return;    
       }
       /*
       *
       * 关闭数据连接
       * 
       * */ 
       public function close()
       {
           if($this->con)
           odbc_close($this->con);
       }
  }//ODBC类结束
   
  
/**
*
* 文件缓存类
* 
* */ 
class Cache extends EasyPHP
   {
       private $cache_time="30";
       private $cache_path="cache";
       public $keys=array();
       public function __construct($cfg=array())
       {
         // $this->config($this->cfg); 
         // $this->init();
         $this->config($cfg);
       }
       /*取得缓存*/ 
       public function get($key)
       {
          $md5key=md5($key); 
          if(!$this->C("cache_on")) return;
          if($this->exist($key))
          {
             $value= $this->readfile($this->cache_path."/".$md5key.".php");
             return $this->unserialize($value);
          }
          else
          {
              return null;
          } 
       }
       /*设置缓存*/ 
       public function set($key,$value=null)
       {
          $md5key=md5($key); 
          if(!$this->C("cache_on"))return false;
          if($value==null) return $this->get($key);  
          $value= $this->serialize($value); 
          if(!$this->exist($key))
          {
            $this->writefile($this->cache_path."/".$md5key.".php",$value,"w");
           if($this->exist($key))
           {
             array_push($this->keys,array($key.".php"=>$key.".php"));  
           }   
            return true;  
          }
          else
          {
           
           $this->writefile($this->cache_path."/".$md5key.".php",$value,"w");   
           //touch($this->cache_path."/".$key.".php");
           return true;
          }   
       }
       /*判断缓存是否存在*/ 
       public function exist($key)
       {
        $md5key=md5($key);
        for($i=0;$i<count($this->keys);$i++)
        {
            foreach ($this->keys[$i] as $k => $v) {
              if($md5key.".php"==$k)
              return $v;
            }
        }
        return 0;
        //$this->dump(array_key_exists($key.".php",$this->keys));
        
       }
       /*清除过期缓存*/ 
       public function clear($key=null)
       {
          if($key==null)
          {
             for($i=0;$i<count($this->keys);$i++)
             {              
              foreach($this->keys[$i] as $k=>  $v) 
              {
                // $this->dump($filename);     
                $filename=$this->cache_path."/".$v;  
                if(file_exists($filename))
                { 
					//$this->dump((time()-filemtime($filename)));
                    
                    if((time()-filemtime($filename))>=$this->cache_time)
                    {
                      if(file_exists($filename))
                      {
                         // $this->dump($this->cache_time);
                          @unlink($filename); 
                      }
                    }   
                }
                else
                {
                  //$this->dump("Hello");  
                }
              }
             }
   
          }
          else
          {
           if(file_exists($this->cache_path."/".md5($key).".php")) 
            @unlink($this->cache_path."/".md5($key).".php");
          } 
     
       }
       /*清除所有缓存*/ 
       public function clear_all()
       {
         for($i=0;$i<count($this->keys);$i++)
         {              
          foreach($this->keys[$i] as $k=>  $v) 
          {
            $filename=$this->cache_path."/".$v;  
            if(file_exists($filename))
            {
                unlink($filename);
            }  
          }
         }  
       }          
       /*设置参数*/ 
       public function config($cfg)
       {
          $this->cache_time=$this->C("cache_time");
          $this->cache_path=$this->C("cache_path"); 
           
       }
       /*初始化缓存*/ 
       public function init()
       {
         if($this->C("cache_on"))
         {  
             $file= scandir($this->cache_path); 
             foreach ($file as $value) 
             {
                if(strpos($value,".")!=0)
                {
                    //$this->dump($value);
                   if(!array_key_exists($value,$this->keys)) 
                   array_push($this->keys,array($value=>$value));
                   
                } 
             }
         }    
       }
       
       public  function __destruct()
       {
           $this->clear();
       }
       
   }//Cache类结束*/   
   

 /**
 *
 * 数据库缓存类
 * 
 *  */ 
class DbCache extends EasyPHP
   {
       private $cache_time="30";
       private $cache_table="cache";
       public function __construct()
       {
       }
       /**
       *
       * 取得缓存
       * 
       * */ 
       public function get($key)
       {
        $md5key=md5($key);   
        return  $this->unserialize( $this->db->scalar("select cache_value from {$this->cache_table} where cache_key='{$md5key}'"));
       }
       /**
       *
       * 设置缓存
       * 
       * */ 
       public function set($key,$value=null,$time=null)
       {
         $time=$time?$time:$this->cache_time;  
         if($this->exist($key))
         {
            $this->db->update($this->cache_table,array("cache_value"=>$this->serialize($value)
            ,"cache_time"=>time(),"past_time"=>time()+$time)," cache_key='".md5($key)."'"); 
         }
         else
         {  
         $this->db->insert($this->cache_table,array("cache_key"=>md5($key),
         "cache_value"=>$this->serialize($value),"cache_time"=>time(),"past_time"=>time()+$time));
         }
       }
       /**
       *
       * 判断缓存是否存在*
       * 
       * */ 
       public function exist($key)
       {
         return $this->db->scalar("select count(*) from {$this->cache_table} where cache_key='".md5($key)."'");
       }
       /**
       *
       * 清除过期缓存 
       * 
       * */
       public function clear($key=null)
       {
         $this->db->delete($this->cache_table,"past_time<{$this->cur_time()}"); 
       }
       /**
       *
       * 清除所有缓存
       * 
       * */
       public function clear_all()
       { 
         $this->db->query("truncate table {$this->cache_table}");
       }
       /**
       *
       * 设置参数
       * 
       * */
       public function config($cfg)
       {
         $this->cache_table=$this->C("db_cache_table");
         $this->cache_time=$this->C("db_cache_time");
         if($this->C("db_cache_on"))
         $this->init();
       }
       /**
       *
       * 初始化缓存
       * 
       * */
       public function init()
       {
         $table_sql="
          CREATE TABLE {$this->cache_table} (                                                                
          `id` bigint(20) NOT NULL auto_increment COMMENT '编号',       
          `cache_key` varchar(50) default NULL COMMENT 'md5缓存健',       
          `cache_value` longtext COMMENT '缓存内容',                  
          `cache_time` int(10) default NULL COMMENT '缓存时间',       
          `past_time` int(10) default NULL COMMENT '缓存过期时间',  
          PRIMARY KEY  (`id`)                                             
        ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8";


       if($this->C("db_cache_on"))
       {
           if($this->db->scalar("show tables like '{$this->cache_table}'")==null)
           {
              $this->db->query($table_sql);  
           }  
       }
       }
       /**
       *
       * 析构函数
       * 
       * */
       public  function __destruct()
       {
         if($this->C("db_cache_on")) 
         $this->clear();  
       }
       /**
       *
       * 当前时间
       * 
       * */
       public function cur_time()
       {
           return time();
       }
       
   }//DbCache类结束  
/**
* @desc 数据库Session类 
*    
*/
class DbSession extends EasyPHP
   {
       private $db_session_time="30";
       private $db_session_table="session";
       public function __construct()
       {
       }
       /**
       *
       * 取得缓存
       * 
       * */ 
       public function get($key)
       {
           if($this->C("db_session_on"))
           {
            $md5key=md5($key);   
            return  ( $this->db->scalar("select cache_value from {$this->db_session_table} where cache_key='{$md5key}'"));
           }
       }
       /**
       *
       * 设置缓存
       * 
       * */ 
       public function set($key,$value=null,$time=null)
       {
         if($this->C("db_session_on"))
         {  
         $time=$time?$time:$this->db_session_time;  
         if($this->exist($key))
         {
            $this->db->update($this->db_session_table,array("cache_value"=>($value)
            ,"cache_time"=>time(),"past_time"=>time()+$time)," cache_key='".md5($key)."'"); 
         }
         else
         {  
         $this->db->insert($this->db_session_table,array("cache_key"=>md5($key),
         "cache_value"=>($value),"cache_time"=>time(),"past_time"=>time()+$time));
         }
         }
       }
       /**
       *
       * 判断缓存是否存在
       * 
       * */ 
       public function exist($key)
       {
         return $this->db->scalar("select count(*) from {$this->db_session_table} where cache_key='".md5($key)."'");
       }
       /**
       *
       * 清除过期缓存 
       * 
       * */
       public function clear($key=null)
       {
           if($this->C("db_session_on")) 
           {
         $this->db->delete($this->db_session_table,"past_time<{$this->cur_time()}"); 
         $this->db->execute("OPTIMIZE TABLE {$this->db_session_table}");
           }
       }
       /**
       *
       * 清除所有缓存
       * 
       * */
       public function clear_all()
       { 
        // $this->db->query("truncate table {$this->db_session_table}");
       }
       /**
       *
       * 设置参数
       * 
       * */
       public function config($cfg)
       {
         $this->db_session_table=$this->C("db_session_table");
         $this->db_session_time=$this->C("db_session_time");
         if($this->C("db_session_on"))
         $this->init();
       }
       /*初始化缓存*/
       public function init()
       {
          $table_sql="
          CREATE TABLE {$this->db_session_table} (                                                                
          `id` bigint(20) NOT NULL auto_increment COMMENT '编号',       
          `cache_key` varchar(50) default NULL COMMENT 'md5缓存健',       
          `cache_value` longtext COMMENT '缓存内容',                  
          `cache_time` int(10) default NULL COMMENT '缓存时间',       
          `past_time` int(10) default NULL COMMENT '缓存过期时间',  
          PRIMARY KEY  (`id`)                                             
        ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8";
       if($this->C("db_session_on"))
       {
           if($this->db->scalar("show tables like '{$this->db_session_table}'")==null)
           {
              $this->db->query($table_sql);  
           }  
       }
       }
       /*析构函数*/
       public  function __destruct()
       { 
         $this->clear();  
       }
       /*当前时间*/
       public function cur_time()
       {
           return time();
       }
       public function open($savePath, $sessName)
       {
           return true;
       }
       public function close()
       {
          $this->clear(); 
          return true;
       }
       public function gc()
       {
          return $this->clear();
       }
        function destroy($key)
       {
         $this->clear($key);  
       }
       
   }//DbSession类结束   
   
   if(file_exists("EasyMail.php"))
   include_once("EasyMail.php");
   
     if(file_exists("EasyFtp.php"))
   include_once("EasyFtp.php");

?>
